<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\erp\logic;
use think\facade\Hook;
use think\DB;
use util\Tree;
use think\facade\Debug;
use think\facade\Cache;
/**
 * 创建管理员
 * @package app\erp\model
 */
class AdminUserlogic{

    /**
     * 首页
     * @author  shiqiang
     * @return array_out(code, message, data)
     */
    public function index($user_id, $store_id = 0, $user_type = 2){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'store_id' 	=> $store_id,
				'user_type' => $user_type
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
            $map = [];//搜索处理
            if($store_id != '') $map[] = ['store_id', '=', $store_id];
            $map[] = ['user_type', '=', $user_type];
			$list = model('ErpAdminUser', 'model') -> where($map) -> order('create_time desc') -> paginate();
			$rel_list = [];
            foreach($list as $key => $value){
				$store_id = $value['store_id'];
				$store_title = '未绑定门店';
				if($store_id > 0 ){
					$store = model('ErpStore', 'model') -> find($store_id);
					if(!empty($store) && $value['user_type'] == 2){
						$store_title = $store['title'];
					}
				}	
				
				$rel_list[$key]['id'] 			= (int)$value['id'];
				$rel_list[$key]['nickName'] 	= (string)$value['nick_name'];
				$rel_list[$key]['storeTitle'] 	= (string)$store_title;
				$rel_list[$key]['createTime'] 	= (int)$value['create_time'];
			}
            $result_list = [];
            $result_list['total']  			= (int)$list -> total();//总数
            $result_list['current_page']	= (int)$list -> currentPage();//页码
            $result_list['last_page']   	= (int)$list -> lastPage();//总页数
            $result_list['per_page']   		= (int)$list -> listRows();//每页条数
            $result_list['data'] 			= $rel_list;
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $result_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 添加
     * @param mobile 	            int  	手机号
     * @param nick_name 	        string  管理员名
     * @param user_type 	        int     1 超级管理员 2门店管理  3视频管理员
     * @param store_id 	        	int     门店id
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function add($user_id, $mobile, $nick_name, $user_type, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 		=> $user_id,
				'mobile'    	=> $mobile,
				'nick_name' 	=> $nick_name,
				'user_type'     => $user_type,
				'store_id' 	    => $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$map = [];
			$map['uid'] = $user_id;
			$admin_info = model('ErpAdminUser', 'model') -> where($map) -> find();
			if(empty($admin_info) || $admin_info['user_type'] != 1){
				DB::rollback();
                return array_out(-1005, 'error1'); //没有权限
			}
			
			//判断手机号是否已经绑定账户
            $res = model('user_center/UcMemberMobile', 'model\user') -> getDataByMobile($mobile);
            if($res['code'] < 0){
				DB::rollback();
                return array_out(-1005, '手机号并未绑定任何账号');
				
			}
			//手机号码是否被绑定了
			$uid = $res['data'] -> uid;
			$map = [];
			$map[] = ['uid', '=', $uid];
			$map[] = ['user_type', '=', $user_type];
			$admin_info = model('ErpAdminUser', 'model') -> where($map) -> find();
			if(!empty($admin_info)){
				DB::rollback();
                return array_out(-1005, '手机号码已被其他账号绑定');
			}
			
			$rel = model('ErpAdminUser','model') -> addData($uid, $nick_name, $user_type, $store_id);
			if($rel['code'] < 0){
				DB::rollback();
                return array_out(-1005, 'error');//添加失败 返回-1005,error
				
			}
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success',$rel['data']);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 编辑
     * @param id 	                string  仓库id
	 * @param mobile 	            int  	手机号
     * @param nick_name 	        string  管理员名
     * @param user_type 	        int     1 超级管理员 2门店管理  3视频管理员
     * @param store_id 	        	int     门店id
     * @author shiqiang
     * @return array_out(code, message, data)
     */
    public function edit($user_id,$id, $mobile, $nick_name, $user_type, $store_id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
                'mobile'    	=> $mobile,
				'nick_name' 	=> $nick_name,
				'user_type'     => $user_type,
				'store_id' 	    => $store_id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$map = [];
			$map['uid'] = $user_id;
			$admin_info = model('ErpAdminUser', 'model') -> where($map) -> find();
			if(empty($admin_info) || $admin_info['user_type'] != 1){
				DB::rollback();
                return array_out(-1005, 'error1'); //没有权限
			}
			
			//判断手机号是否已经绑定账户
            $res = model('user_center/UcMemberMobile', 'model\user') -> getDataByMobile($mobile);
            if($res['code'] < 0){
				DB::rollback();
                return array_out(-1005, '手机号并未绑定任何账号');
				
			}
			$uid = $res['data'] -> uid;
			$map = [];
			$map[] = ['id', 'neq', $id];
			$map[] = ['uid', '=', $uid];
			$map[] = ['user_type', '=', $user_type];
			$admin_info = model('ErpAdminUser', 'model') -> where($map) -> find();
            if(!empty($admin_info)){
				DB::rollback();
                return array_out(-1005, '手机号码已被其他账号绑定');
			}
			$rel = model('ErpAdminUser','model') -> editData($id, $nick_name, $user_type, $store_id);
			if($rel['code'] < 0){
				DB::rollback();
                return array_out(-1005, 'error');//编辑失败 返回-1005,error
				
			}
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }

    /**
     * 删除
     * @param int $id
     * @author shiqiang
     * @return bool
     */
    public function delete($user_id, $id){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$rel = model('ErpAdminUser') -> deleteData($id);
			if($rel['code'] < 0){
				return array_out(-1005, 'error');//删除失败 返回-1005,error
			}
			
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success');
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
    }
	
	 /**
     * 详情
     * @param int $id
     * @author shiqiang
     * @return bool
     */
	public function details($user_id, $id){
		DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
				'user_id' 	=> $user_id,
				'id' 		=> $id,
            ];
            /********行为参数赋值（*）********/
     
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            /********业务逻辑********/
			$info = model('ErpAdminUser', 'model') -> find($id);
			
			$store_id = $info['store_id'];
			$store_title = '未绑定门店';
			if($store_id > 0 ){
				$store = model('ErpStore', 'model') -> find($store_id);
				if(!empty($store) && $info['user_type'] == 2){
					$store_title = $store['title'];
				}
			}	
			
			$map = [];
			$map['uid'] = $info['uid'];
			$mobile = model('user_center/UcMemberMobile', 'model\user') -> where($map) -> find() -> mobile;
			
			$rel_list['id'] 			= (int)$info['id'];
			$rel_list['nickName'] 		= (string)$info['nick_name'];
			$rel_list['mobile'] 		= (int)$mobile;
			$rel_list['userType'] 		= (int)$info['user_type'];
			$rel_list['storeId'] 		= (int)$info['store_id'];
			$rel_list['storeTitle'] 	= (string)$store_title;
			$rel_list['createTime'] 	= (int)$info['create_time'];
            /********业务逻辑********/
			
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
			DB::commit();
            return array_out(200, 'success', $rel_list);
            /********逻辑返回********/
			
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());//异常错误 -9999
        }
	}
}